import java.util.Deque;
import java.util.LinkedList;

public class WidthOfBinaryTree {

    public int widthOfBinaryTree1(TreeNode root) {
        if (root == null) return 0;
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        root.val = 0;
        int ans = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            int start = 0;
            int end = 0;
            for (int i = 0; i < size; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) {
                    node.left.val = node.val * 2 + 1;
                    queue.add(node.left);
                }
                if (node.right != null) {
                    node.right.val = node.val * 2 + 2;
                    queue.add(node.right);
                }
                if (i == 0) start = node.val;
                if (i == size - 1) end = node.val;
            }
            ans = Math.max(ans, end - start + 1);
        }
        return ans;
    }

    public int widthOfBinaryTree(TreeNode root) {
        Deque<TreeNode> queue = new LinkedList<>();
        Deque<Integer> queueIndex = new LinkedList<>();
        queue.add(root);
        queueIndex.add(0);
        int ans = 0;
        while (!queue.isEmpty()) {
            ans = Math.max(ans, queueIndex.peekLast() - queueIndex.peekFirst());
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                Integer index = queueIndex.poll();
                if (poll.left != null) {
                    queue.add(poll.left);
                    queueIndex.add(index * 2 + 1);
                }
                if (poll.right != null) {
                    queue.add(poll.right);
                    queueIndex.add(index * 2 + 2);
                }
            }
        }
        return ans + 1;
    }
}
